package com.demo.rxjavademo.http;


import android.os.Environment;

import com.demo.rxjavademo.app.App;
import com.demo.rxjavademo.utils.NetworkUtil;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/12/19.
 */

public class ApiClient {
    private static Retrofit mRetrofit = null;

    public static Retrofit retrofit() {

        if (mRetrofit == null) {
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            /**
             *设置缓存，代码略
             */
            File httpCacheFile = new File(Environment.getExternalStorageDirectory(), "HttpCache");
            int cacheSize = 10 * 1024 * 1024;
            Cache cache = new Cache(httpCacheFile, cacheSize);


            /**
             *  公共参数，代码略
             */

            /**
             * 设置头，代码略
             */

            /**
             * Log信息拦截器，代码略
             * 只能对缓存Get请求，不能是用Post请求
             */
            Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request();
                    Response response = chain.proceed(request);
                    if (NetworkUtil.getInstance().isNetworkConnected(App.getInstance().getContext())) {
                        int maxAge = 60;//缓存失效时间，单位为秒
                        return response.newBuilder()
                                .removeHeader("Pragma")//清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                                .header("Cache-Control", "public ,max-age=" + maxAge)
                                .build();
                    }
                    return response;
                }
            };

            //日志拦截器
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            /**
             * 设置cookie，代码略
             */

            /**
             * 设置超时和重连，代码略
             */
            //以上设置结束，才能build(),不然设置白搭
            OkHttpClient okHttpClient = builder
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
//                    .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                    .addInterceptor(interceptor)//添加日志拦截器
                    .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)//添加缓存拦截器
                    .cache(cache)
                    .build();

            mRetrofit = new Retrofit.Builder()
                    .baseUrl(ApiStores.API_SERVER_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();
        }
        return mRetrofit;

    }
}


